<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="平台" prop="platform">
        <el-select
          v-model="queryParams.platform"
          placeholder="请选择平台"
          clearable
        >
          <el-option
            v-for="dict in dict.type.app_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="版本号" prop="appVersion">
        <el-input
          v-model="queryParams.appVersion"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="热更新版本号" prop="hotUpdateVersion">
        <el-input
          v-model="queryParams.hotUpdateVersion"
          placeholder="请输入热更新版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否强制更新" prop="isForce">
        <el-select
          v-model="queryParams.isForce"
          placeholder="请选择是否强制更新"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:update:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:update:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:update:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:update:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="updateList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="平台" align="center" prop="platform">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.app_type" :value="scope.row.platform" />
        </template>
      </el-table-column>
      <el-table-column label="版本号" align="center" prop="appVersion" />
      <el-table-column
        label="热更新版本号"
        align="center"
        prop="hotUpdateVersion"
      />
      <el-table-column label="是否强制更新" align="center" prop="isForce">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_yes_no"
            :value="scope.row.isForce"
          />
        </template>
      </el-table-column>
      <el-table-column label="更新类型" align="center" prop="updateType" />
      <el-table-column label="更新说明" align="center" prop="description" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
            {{ scope.row.status == 1 ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:update:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:update:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改App 热更新版本记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="平台" prop="platform">
          <el-select v-model="form.platform" placeholder="请选择平台">
            <el-option
              v-for="dict in dict.type.app_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="版本号" prop="appVersion">
          <el-input v-model="form.appVersion" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="热更新版本号" prop="hotUpdateVersion">
          <el-input
            v-model="form.hotUpdateVersion"
            placeholder="请输入热更新版本号"
          />
        </el-form-item>
        <el-form-item label="更新包下载地址" prop="packageUrl">
          <!-- <file-upload
            v-model="form.packageUrl"
            :fileSize="100"
            :fileType="['apk']"
          /> -->
          <el-upload
            :file-list="apkUrlFileList"
            class="upload-demo"
            :action="apkUrlUploadURL"
            :on-remove="apkUrlHandleRemove"
            :before-upload="beforeAvatarUpload"
            :on-success="apkUrlHandleSuccess"
            show-file-list
            :headers="headers"
            :on-preview="apkUrlHandlePreview"
            :limit="1"
          >
            <el-button
              size="small"
              v-if="apkUrlFileList.length == 0"
              type="primary"
              >添加附件</el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="是否强制更新" prop="isForce">
          <el-select v-model="form.isForce" placeholder="请选择是否强制更新">
            <el-option
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUpdate,
  getUpdate,
  delUpdate,
  addUpdate,
  updateUpdate,
} from "@/api/system/update";
import { getToken } from "@/utils/auth";

export default {
  name: "Update",
  dicts: ["sys_yes_no", "app_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // App 热更新版本记录表格数据
      updateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        platform: null,
        appVersion: null,
        hotUpdateVersion: null,
        isForce: null,
        updateType: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        platform: [
          { required: true, message: "平台不能为空", trigger: "change" },
        ],
        appVersion: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
        ],
        hotUpdateVersion: [
          { required: true, message: "热更新版本号不能为空", trigger: "blur" },
        ],
        packageUrl: [
          {
            required: true,
            message: "更新包下载地址不能为空",
            trigger: "blur",
          },
        ],
      },
      apkUrlFileList: [],
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      apkUrlUploadURL: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 上传成功
    apkUrlHandleSuccess(res, file, apkUrlFileLists) {
      this.form.packageUrl = res.url;
      this.apkUrlFileList = apkUrlFileLists;
    },
    beforeAvatarUpload(uploadFile) {
      const fileType = uploadFile.name;
      if (fileType.endsWith(".apk")) {
        return true;
      }
      ElMessage.error("文件类型不是.apk");
      return false;
    },

    //附件下载
    apkUrlHandlePreview(uploadFile) {
      let a = document.createElement("a");
      let event = new MouseEvent("click");
      a.download = uploadFile.name;
      a.href = uploadFile.url;
      a.dispatchEvent(event);
    },

    //删除文件
    apkUrlHandleRemove(uploadFile, uploadFiles) {
      this.apkUrlFileList = uploadFiles;
      this.form.packageUrl = "";
    },
    /** 查询App 热更新版本记录列表 */
    getList() {
      this.loading = true;
      listUpdate(this.queryParams).then((response) => {
        this.updateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        platform: null,
        appVersion: null,
        hotUpdateVersion: null,
        packageUrl: null,
        isForce: null,
        updateType: null,
        description: null,
        createTime: null,
        updateTime: null,
        status: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加App 热更新版本记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.apkUrlFileList = [];
      const id = row.id || this.ids;
      getUpdate(id).then((response) => {
        this.form = response.data;
        if (this.form.packageUrl) {
          let fileApk = {
            url: "",
            name: "",
            type: "",
          };
          fileApk.url = this.form.packageUrl;
          const fileName = this.form.packageUrl.split(".");
          const fileExt = fileName[fileName.length - 1];
          fileApk.name = fileName;
          fileApk.type = "application/vnd.android.package-archive";
          this.apkUrlFileList.push(fileApk);
        } else {
          this.apkUrlFileList = [];
        }
        this.open = true;
        this.title = "修改App 热更新版本记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUpdate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUpdate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除App 热更新版本记录编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUpdate(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/update/export",
        {
          ...this.queryParams,
        },
        `update_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
